# coding=utf-8
import time
from decimal import Decimal

from django.db import transaction
from django.db.models import Q
from rest_framework.utils import json

from worldcup.apps.userModel.models import OrderHead, OrderDetail, Sku, PayDeal
from worldcup.commons.CommonResult import rest, CommonResult
from worldcup.commons.IdGenerator import generateId
from worldcup.commons.email_sender import send_mail
from worldcup.rest_views.shopcart_rest_view import add_shopcart


@transaction.atomic
@rest
def create_order(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	# 参数校验
	openid = reqest_params["openid"]
	if openid == "" or openid is None:
		return CommonResult(-1, "openid不能为空")
	details = reqest_params["details"]
	if details is None or len(details) == 0:
		return CommonResult(-1, "details不能为空")
	is_shoppingcart = reqest_params.get("isShoppingCart")
	if is_shoppingcart is None:
		is_shoppingcart = False
	is_express = reqest_params["isExpress"]
	if is_express is None:
		return CommonResult(-1, "isExpress不能为空")
	order = OrderHead()
	order_code = generateId()
	order.order_code = order_code
	order.order_status = 10   # 待支付
	order.pay_status = 10    # 未支付
	order.openid = openid
	order.express_type = 1 if is_express else 2
	order.status = 1
	now = int(time.time())
	order.order_time = now
	order.created_at = now
	order.updated_at = now

	total_qty = 0
	total_amount = Decimal(0)

	for detail in details:
		order_detail = OrderDetail()
		order_detail.order_code = order_code
		sku_code = detail["skuCode"]
		qty = detail["qty"]
		order_detail.sku_code = sku_code
		sku = Sku.objects.values("sku_name", "sku_images", "origin_price", "price", "sku_specification").filter(sku_code=sku_code).get()
		# todo inventory decrease
		order_detail.sku_name = sku["sku_name"]
		order_detail.sku_image = sku["sku_images"]
		order_detail.price = sku["price"]
		order_detail.origin_price = sku["origin_price"]
		order_detail.sku_specification = sku["sku_specification"]
		order_detail.qty = qty
		order_detail.created_at = now
		order_detail.updated_at = now

		total_qty += qty
		total_amount = total_amount + Decimal(qty) * Decimal(sku["price"])
		order_detail.save()

		# 如果是购物车购买的，则需操作购物车
		if is_shoppingcart:
			add_shopcart(openid, sku_code, 0 - qty)
	order.total_qty = total_qty
	if is_express:
		total_amount = total_amount + Decimal(10)
	order.total_amount = total_amount
	order.save()
	return CommonResult(0, {"orderCode": str(order_code), "totalAmount": str(total_amount)})


@rest
def list_order(request):
	results = []
	openid = request.GET.get("openid")
	if openid is None or openid == "":
		return CommonResult(-1, "openid不能为空")
	order_heads = OrderHead.objects.filter(openid=openid, status=1, order_status__gt=10).filter(~Q(order_status=40)).order_by("-created_at").all()
	for order_head in order_heads:
		order_details = OrderDetail.objects.filter(order_code=order_head.order_code).exclude(status=0).all()
		skus = []
		for order_detail in order_details:
			skus.append({
				"skuCode": order_detail.sku_code,
				"skuName": order_detail.sku_name,
				"skuSpecification": order_detail.sku_specification,
				"skuImage": order_detail.sku_image,
				"qty": order_detail.qty,
				"origin": None if order_detail.origin_price is None else str(order_detail.origin_price),
				"price": str(order_detail.price),
			})
		results.append({
			"orderCode": str(order_head.order_code),
			"totalAmount": str(order_head.total_amount),
			"orderStatus": order_head.order_status,
			"createdAt": order_head.created_at,
			"isExpress": True if order_head.express_type == 1 else False,
			"expressCompany": order_head.express_type,
			"expressCode": order_head.express_code,
			"skus": skus
		})
	return CommonResult(0, results)


@rest
def get_order(request):

	order_code = request.GET.get("orderCode")
	if order_code == "" or order_code is None:
		return CommonResult(0, {})
	order_heads = OrderHead.objects.filter(order_code=order_code).all()
	if len(order_heads) == 0:
		return CommonResult(0, {})
	order_head = order_heads[0]
	order_details = OrderDetail.objects.filter(order_code=order_head.order_code).exclude(status=0).all()
	details = []
	for order_detail in order_details:
		details.append({
			"skuCode": order_detail.sku_code,
			"skuName": order_detail.sku_name,
			"skuSpecification": order_detail.sku_specification,
			"skuImage": order_detail.sku_image,
			"qty": order_detail.qty,
			"origin": None if order_detail.origin_price is None else str(order_detail.origin_price),
			"price": str(order_detail.price),
		})
	return CommonResult(0, {
		"orderCode": str(order_code),
		"orderStatus": order_head.order_status,
		"expressCompany": order_head.express_company,
		"expressCode": order_head.express_code,
		"createdAt": order_head.created_at,
		"totalAmount": str(order_head.total_amount),
		"details": details
	})



# @transaction.atomic
# @rest
# def cancel_order(request):
# 	try:
# 		reqest_params = json.loads(request.body)
# 	except ValueError:
# 		return CommonResult(-1, "数据格式错误")
# 	# 参数校验
# 	openid = reqest_params["openid"]
# 	if openid == "" or openid is None:
# 		return CommonResult(-1, "openid不能为空")
# 	order_code = reqest_params["orderCode"]
# 	if order_code == "" or order_code is None:
# 		return CommonResult(-1, "orderCode不能为空")
#
# 	orders = OrderHead.objects.filter(order_code=order_code, openid=openid).all()
# 	if len(orders) == 0:
# 		return CommonResult(-1, "没有对应的订单号")
# 	order = orders[0]


@transaction.atomic
@rest
def refund_order(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	order_code = reqest_params.get("orderCode")
	if order_code is None:
		return CommonResult(-1, "orderCode为空")
	reason = reqest_params.get("reason")
	order_head = OrderHead.objects.filter(order_code=order_code).get()
	if order_head.order_status == 10:
		return CommonResult(-1, "订单不允许退款")
	if order_head.order_status >= 23:
		return CommonResult(-1, "此订单状态不允许退款")
	order_head.order_status = 50
	order_head.pay_status = 50
	order_head.updated_at = int(time.time())
	order_head.save()

	pay_deal = PayDeal.objects.filter(order_id=order_code).get()
	pay_deal.pay_status = 6
	pay_deal.updated_at = int(time.time())
	pay_deal.save()

	## 发邮件
	send_mail("退款申请", "orderCode = " + str(order_code) + " 退款原因：" + reason)
	return CommonResult(0, "success")


@rest
def finish_order(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	order_code = reqest_params.get("orderCode")
	if order_code is None:
		return CommonResult(-1, "orderCode为空")
	order_head = OrderHead.objects.filter(order_code=order_code).get()
	order_head.order_status = 30
	order_head.save()
	return CommonResult(0, "success")

@rest
def delete_order(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	order_code = reqest_params.get("orderCode")
	if order_code is None:
		return CommonResult(-1, "orderCode为空")
	order_head = OrderHead.objects.filter(order_code=order_code).get()
	order_head.status = 0
	order_head.save()
	return CommonResult(0, "success")




